package cn.szzsi.common.kit;

import cn.szzsi._Config;
import cn.szzsi.common.model.Member;
import cn.szzsi.common.model.SiteConfig;
import cn.szzsi.common.model.Template;
import cn.szzsi.core.dubbo.WeChatDubboService;
import cn.szzsi.service.ApiInterface;
import com.jfinal.core.Controller;
import com.jfinal.core.JFinal;
import com.jfinal.kit.StrKit;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.beanutils.PropertyUtils;

import javax.servlet.http.HttpServletRequest;
import java.beans.PropertyDescriptor;
import java.io.File;
import java.lang.reflect.InvocationTargetException;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 工具类 - 公用
 *
 */

public class CommonUtil {

	public static String PLATFROM_FLAG = "-1";
	public static String BUSINESS_TEMPLATE_PATH = "path";
	public static String PLATFORM_MEMBER = "-1";//平台的会员
	public static String PLATFORM_BUSINESS = "0";//平台的商户
	public static String BROWSER_TYPE="browserType";//浏览器类型
	public static String SESSION_ADMIN="___session_admin";//admin的session
	public static String TEMPLATE_PATH="/WEB-INF/views";//admin的session

	public static String  FILES="file_db";//files数据源


	/**
	 * 获取6位数纯数字验证码
	 * @return
	 */
	public static String getSixRandom(){
		Random r = new Random();
		StringBuffer captcha1 = new StringBuffer();
		for (int i = 0; i < 6; i++) {
			captcha1.append(r.nextInt(9)+"");
		}
		String captcha = new String(captcha1);
		return captcha;
	}
	/**
	 * 随机获取UUID字符串(无中划线)
	 * 
	 * @return UUID字符串
	 */
	public static String getUUID() {
		String uuid = UUID.randomUUID().toString();
		return uuid.substring(0, 8) + uuid.substring(9, 13) + uuid.substring(14, 18) + uuid.substring(19, 23) + uuid.substring(24);
	}

	/**
	 * 获取某个会员的shopId
	 * @param member
	 * @return
	 */
	public static String getShopId(Member member){
		String uid="";
		if("super".equals(member.getStr("b_shoprank"))){
			uid=member.getStr("id");
		}else{
			if(StrKit.notBlank(member.getStr("shopId"))&&!member.getStr("shopId").equalsIgnoreCase("0")){
				uid = member.getStr("shopId");
			} else{
				uid=member.getStr("b_shoprank");
			}
		}
		return uid;
	}

	/**
	 * 随机获取字符串
	 * 
	 * @param length
	 *            随机字符串长度
	 * 
	 * @return 随机字符串
	 */
	public static String getRandomString(int length) {
		if (length <= 0) {
			return "";
		}
		char[] randomChar = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'q', 'w', 'e', 'r', 't', 'y', 'u', 'i', 'o', 'p', 'a', 's', 'd',
				'f', 'g', 'h', 'j', 'k', 'l', 'z', 'x', 'c', 'v', 'b', 'n', 'm' };
		Random random = new Random();
		StringBuffer stringBuffer = new StringBuffer();
		for (int i = 0; i < length; i++) {
			stringBuffer.append(randomChar[Math.abs(random.nextInt()) % randomChar.length]);
		}
		return stringBuffer.toString();
	}

	/**
	 * 根据指定长度 分隔字符串
	 * 
	 * @param str
	 *            需要处理的字符串
	 * @param length
	 *            分隔长度
	 * 
	 * @return 字符串集合
	 */
	public static List<String> splitString(String str, int length) {
		List<String> list = new ArrayList<String>();
		for (int i = 0; i < str.length(); i += length) {
			int endIndex = i + length;
			if (endIndex <= str.length()) {
				list.add(str.substring(i, i + length));
			} else {
				list.add(str.substring(i, str.length() - 1));
			}
		}
		return list;
	}

	/**
	 * 将字符串List转化为字符串，以分隔符间隔.
	 * 
	 * @param list
	 *            需要处理的List.
	 *            
	 * @param separator
	 *            分隔符.
	 * 
	 * @return 转化后的字符串
	 */
	public static String toString(List<String> list, String separator) {
		StringBuffer stringBuffer = new StringBuffer();
		for (String str : list) {
			stringBuffer.append(separator + str);
		}
		stringBuffer.deleteCharAt(0);
		return stringBuffer.toString();
	}

	/**
	 * 比较同一类型class,orig 中非NULL值的属性和dest不同的值到resultBean里面
	 * 
	 * @param dest
	 *            要比较的BEAN
	 * @param orig
	 *            原来BEAN
	 * @param result
	 *            结果BEAN
	 * @throws InvocationTargetException
	 * @throws IllegalAccessException
	 */
	public static void differBeanNotNullPropertyToOtherBean(Object dest, Object orig, Object result) throws IllegalAccessException, InvocationTargetException {
		// Validate existence of the specified beans
		if (dest == null) {
			throw new IllegalArgumentException("No destination bean specified");
		}
		if (orig == null) {
			throw new IllegalArgumentException("No origin bean specified");
		}
		if (result == null) {
			throw new IllegalArgumentException("No result bean specified");
		}

		if (!dest.getClass().toString().equals(orig.getClass().toString())) {
			throw new IllegalArgumentException("No same bean class");
		}
		if (orig instanceof Map) {
			throw new IllegalArgumentException("No support map");
		}

		/* if (orig is a standard JavaBean) */
		PropertyDescriptor origDescriptors[] = PropertyUtils.getPropertyDescriptors(orig);
		for (int i = 0; i < origDescriptors.length; i++) {
			String name = origDescriptors[i].getName();
			if ("class".equals(name)) {
				continue; // No point in trying to set an object's class
			}
			if (PropertyUtils.isReadable(orig, name) && PropertyUtils.isWriteable(dest, name)) {
				try {
					Object value1 = PropertyUtils.getSimpleProperty(orig, name);
					Object value2 = PropertyUtils.getSimpleProperty(dest, name);
					if (value2 != null && !value2.equals(value1)) {
						if (PropertyUtils.isReadable(result, name) && PropertyUtils.isWriteable(result, name)) {
							BeanUtils.copyProperty(result, name, value2);
						}
					}
				} catch (NoSuchMethodException e) {
				}
			}
		}

	}

	/**
	 * 比较一个对象，如是这个对象的某一个属性不为空，把他copy到另一个有这个属性的bean中
	 * 
	 * @param target
	 *            要copy到的bean
	 * @param source
	 *            原来BEAN
	 * @throws InvocationTargetException
	 * @throws IllegalAccessException
	 */
	public static void copyProperties(Object target, Object source){
		// Validate existence of the specified beans
		if (target == null) {
			throw new IllegalArgumentException("No destination bean specified");
		}
		if (source == null) {
			throw new IllegalArgumentException("No origin bean specified");
		}

		if (source instanceof Map) {
			throw new IllegalArgumentException("No support map");
		}

		/* if (orig is a standard JavaBean) */
		PropertyDescriptor sourceDescriptors[] = PropertyUtils.getPropertyDescriptors(source);
		for (int i = 0; i < sourceDescriptors.length; i++) {
			String name = sourceDescriptors[i].getName();
			if ("class".equals(name)) {
				continue; // No point in trying to set an object's class
			}
			if (PropertyUtils.isReadable(source, name) && PropertyUtils.isWriteable(target, name)) {
				try {
					Object sourceValue = PropertyUtils.getSimpleProperty(source, name);
					if (sourceValue != null) {
						if (PropertyUtils.isReadable(target, name) && PropertyUtils.isWriteable(target, name)) {
							BeanUtils.copyProperty(target, name, sourceValue);
						}
					}
				} catch (NoSuchMethodException e) {
					e.printStackTrace();
				} catch (IllegalAccessException e) {
					e.printStackTrace();
				} catch (InvocationTargetException e) {
					e.printStackTrace();
				}
			}
		}

	}

	/**
	 * 根据request来判断访问的是pc还是wap
	 * @param request
     * @return
     */
	public static boolean  isMobileDevice(HttpServletRequest request){
		boolean isMoblie = false;
		String[] mobileAgents = { "iphone", "android", "phone", "mobile",
				"wap", "netfront", "java", "opera mobi", "opera mini", "ucweb",
				"windows ce", "symbian", "series", "webos", "sony",
				"blackberry", "dopod", "nokia", "samsung", "palmsource", "xda",
				"pieplus", "meizu", "midp", "cldc", "motorola", "foma",
				"docomo", "up.browser", "up.link", "blazer", "helio", "hosin",
				"huawei", "novarra", "coolpad", "webos", "techfaith",
				"palmsource", "alcatel", "amoi", "ktouch", "nexian",
				"ericsson", "philips", "sagem", "wellcom", "bunjalloo", "maui",
				"smartphone", "iemobile", "spice", "bird", "zte-", "longcos",
				"pantech", "gionee", "portalmmm", "jig browser", "hiptop",
				"benq", "haier", "^lct", "320x320", "240x320", "176x220",
				"w3c ", "acs-", "alav", "alca", "amoi", "audi", "avan", "benq",
				"bird", "blac", "blaz", "brew", "cell", "cldc", "cmd-", "dang",
				"doco", "eric", "hipt", "inno", "ipaq", "java", "jigs", "kddi",
				"keji", "leno", "lg-c", "lg-d", "lg-g", "lge-", "maui", "maxo",
				"midp", "mits", "mmef", "mobi", "mot-", "moto", "mwbp", "nec-",
				"newt", "noki", "oper", "palm", "pana", "pant", "phil", "play",
				"port", "prox", "qwap", "sage", "sams", "sany", "sch-", "sec-",
				"send", "seri", "sgh-", "shar", "sie-", "siem", "smal", "smar",
				"sony", "sph-", "symb", "t-mo", "teli", "tim-", /*"tosh",*/ "tsm-",
				"upg1", "upsi", "vk-v", "voda", "wap-", "wapa", "wapi", "wapp",
				"wapr", "webc", "winw", "winw", "xda", "xda-",
				"Googlebot-Mobile" };
		if (request.getHeader("User-Agent") != null) {
			for (String mobileAgent : mobileAgents) {
				if (request.getHeader("User-Agent").toLowerCase().indexOf(mobileAgent) >= 0) {
					isMoblie = true;
					break;
				}
			}
		}
		return isMoblie;
	}

	//根据uid和访问类型获(wap或者pc)取模板路径
	public static String getPathByUidAndType(String uid, boolean isMobileDevice){
		String path=null;
		Template businessTemplate = null;
		if(isMobileDevice){
			//wap访问
			businessTemplate= Template.getByUseridAndAgent(uid,"wap");
		}else{
			//pc访问
			businessTemplate= Template.getByUseridAndAgent(uid,"pc");
		}

		if(businessTemplate!=null){
			path = businessTemplate.getStr("path");
		}else{
			path=null;
		}
		return path;
	}

	public static String getRealTemplatePath(String path, String name){
		File file =new File(JFinal.me().getServletContext().getRealPath("template")+"/"+path+"/html/"+name);
		if(file.exists()){
			return "/template/"+path+"/html/"+name;
		}else{
			return "/template/default/html/"+name;
		}
	}

	/**
	 * 判断字符串是否数值
	 * @param str
	 * @return true:是数值 ；false：不是数值
	 * @author:WD_SUHUAFU
	 */
	public static boolean isNumber(String str)
	{
		Pattern pattern = Pattern.compile("^[0-9]+(.[0-9]*)?$");
		Matcher match=pattern.matcher(str);
		return match.matches();
	}

	//TODO
	public static String getWebname(HttpServletRequest request){
		StringBuffer url = request.getRequestURL();
		return url.delete(url.length() - request.getRequestURI().length(), url.length()).append("/").toString();
	}

	/**
	 * 通过后台配置的路径来获取某一个商户的网址，不填写默认取配置文件中的web.url
	 * 和getwebname方法不一样，他是商户的毁于哦安获取网址的方法,可能待改进
	 * @param sc
	 * @return
	 */
	public static String getBusinessWebName(SiteConfig sc){

		if(sc != null && StrKit.notBlank(sc.getStr("shopUrl")))
			return sc.getStr("shopUrl");

		return _Config.p.get("mall_web.url");

	}

	/**
	 * 获取完整访问路径
	 */
	public static String getBackUrl(Controller c){
		if(StrKit.isBlank(c.getRequest().getQueryString())){
			return "https://" + c.getRequest().getServerName() + c.getRequest().getContextPath() + c.getRequest().getServletPath()+ "?a=1";
		}else{
			return "https://" + c.getRequest().getServerName() + c.getRequest().getContextPath() + c.getRequest().getServletPath() + "?" +c.getRequest().getQueryString();
		}

	}

	/**
	 * 是否是微信登陆
	 * @param c
	 * @return
	 */
	public static boolean isWeixinBrowser(Controller c){
		String userAgent=c.getHeader("user-agent");//获取浏览器类型
		if (userAgent.toLowerCase().indexOf("micromessenger") != -1) {
			return true;
		}else{
			return false;
		}
	}

	/*public static String getAccessToken(String shopId){
		String result= HttpKit.post(WeChatUrl.getAccessToken+"/"+shopId,"");//获取access_token
		JSONObject jo=new JSONObject(result);
		System.out.println(jo);
		String access_token=jo.getJSONObject("data").getString("accessToken");
		return access_token;
	}*/
	public static String getAccessToken(String shopId){
		ApiInterface apiInterface= WeChatDubboService.getInstance().imports(ApiInterface.class);
		String access_token=apiInterface.getAccessToken(shopId);
		return access_token;
	}




}